package com.ice.body.business.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.ice.base.controller.BaseController;
import com.ice.base.model.SysLoginModel;
import com.ice.base.result.ResponseResult;
import com.ice.base.result.AjaxResult;
import com.ice.base.util.BaseUtil;
import com.ice.base.util.IOUtil;
import com.ice.base.util.RedisUtil;
import com.ice.base.util.VoiceUtil;
import com.ice.body.business.model.ReagentStock;
import com.ice.body.business.service.*;
import com.ice.body.business.vo.ReagentEpcVo;
import com.ice.body.hardware.model.*;
import com.ice.body.hardware.service.DeviceIoService;
import com.ice.body.hardware.service.DeviceMachineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created with GuoYanBin.
 * Description:
 * Date: 2021-06-23
 * Time: 02:25
 */
@RestController
@ApiIgnore( value = "通用业务接口-（校验等）")
public class BusinessController extends BaseController{
    //---------------------------业务接口-审批单-----------------------start
    @Resource
    private RedisUtil redisUtil;
    @Resource
    ReagentStockService reagentStockService;
    @Resource
    DeviceMachineService deviceMachineService;
    @Resource
    private VoiceUtil voiceUtil;
    @Resource
    private IOUtil ioUtil;
    @Resource
    private DeviceIoService deviceIoService;

 /*   *//**
     * @param
     *//*
    @ApiOperation(value = "结算按钮")
    @PostMapping("/api_p/settlement")
    public AjaxResult<T> settlement(HttpServletRequest request){
        Result r = ResponseResult.error();
        String ip = BaseUtil.getIPAddress(request);
        DeviceMachineModel macModel = deviceMachineService.getByIp(ip);
        if (null == macModel){
            return ;
        }
        String ip = "192.168.100.188";
        try{
            DeviceVoiceModel voiceModel = deviceVoiceService.getByIp(ip);
            String warehouseId = voiceModel.getWarehouseId();
            redisUtil.set(warehouseId+"settlement",1);
            voiceUtil.sendVoice(voiceModel.getIp(),voiceModel.getPort(),"开启结算,请刷脸出门！");
            r = ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return r;
    }
*/



    @ApiOperation(value = "查询当前试剂库中用户")
    @PostMapping("/api_p/loadUserSelect")
    public AjaxResult<SysLoginModel> loadUserSelect(HttpServletRequest request){
        String ip = BaseUtil.getIPAddress(request);
        AjaxResult r = ResponseResult.success();

        List<SysLoginModel> selectList = (List<SysLoginModel>)redisUtil.get(1+"userList");
       r.setData(selectList);
        return r;
    }

    @ApiOperation(value = "设置室内使用-中控台才有的功能")    @PostMapping("/api_p/setUseInRoom")
    public void updateIfOutByEpc(@RequestParam("epcCode") String epcCode,HttpServletRequest request){
        String ip = BaseUtil.getIPAddress(request);
        DeviceMachine machine = deviceMachineService.getByIp(ip);
        if(machine == null){
            return;
        }
        String warehouseId = machine.getWarehouseId();
        List<ReagentEpcVo> ckEcList = (List<ReagentEpcVo>) redisUtil.get(warehouseId+"ckEcList");
        for(ReagentEpcVo r :ckEcList){
            if(epcCode.equals(r.getEpcCode())){
                r.setIfOut("2");
                break;
            }
        }
        redisUtil.set(warehouseId+"ckEcList",ckEcList);
    }

    @ApiOperation(value = "设置入库（大门敞开）")
    @PostMapping("/api_p/rkOpenTheDoor")
    public AjaxResult<T> rkOpenTheDoor(@RequestParam("warehouseId") String warehouseId){
        AjaxResult r = ResponseResult.success();
        List<DeviceIo> list = deviceIoService.getByWarehouseId(warehouseId);
        if(!CollectionUtils.isEmpty(list)){
            //时间排序，门的IO一定要放在时间靠后的第一路
            // 开启IO模块1命令
            ioUtil.operIo(list.get(0).getIp(),list.get(0).getPort(),"CCDDA10100010001A448");
        }
        return r;
    }

    @ApiOperation(value = "设置出库（关所有设备）")
    @PostMapping("/api_p/ckCloseTheDoor")
    public AjaxResult<T> ckCloseTheDoor(@RequestParam("warehouseId") String warehouseId){
        AjaxResult r = ResponseResult.success();
        List<DeviceIo> list = deviceIoService.getByWarehouseId(warehouseId);
        if(null != list && list.size()>0){
            //关闭所有
            for (DeviceIo model:list) {
                ioUtil.operIo(model.getIp(),model.getPort(),"CCDDA1010000FFFFA040");
            }
        }
        return r;
    }


    /**
     * 1 入库 2归还 3 出库
     * @param `warehouseId
     * @param dataType
     */
    @ApiOperation(value = "中控台查询扫描数据")
    @PostMapping("/api_p/getRfidData")
    public HashMap<String,Object> getRfidData(Integer dataType,HttpServletRequest request){
       HashMap<String,Object> returnMap = new HashMap();
        String ip = BaseUtil.getIPAddress(request);
     /*   DeviceConsoleModel model =  deviceConsoleService.getByIp(ip);
        if (null == model){
            return ;
        }*/
        // warehouseId = model.getWarehouseId().toString();
        String warehouseId ="1";
//        DeviceMachineModel macModel = deviceMachineService.getByIp(ip);

       // ReagentStockModel stockModel = reagentStockService.getByEpcCode(epcCode);
//        if(1 == dataType){
            List<ReagentStock> rkList = redisUtil.get(warehouseId +"rkList") == null?new ArrayList<>():(ArrayList)redisUtil.get(warehouseId +"rkList");   //入库
            returnMap.put("rkData",rkList);
//        }else if (2 == dataType){
            List<ReagentStock> ghList = redisUtil.get(warehouseId +"ghList") == null?new ArrayList<>():(ArrayList)redisUtil.get(warehouseId +"ghList");   //归还
            returnMap.put("ghData",ghList);
//        }else if (3 == dataType){
            List<ReagentStock> ckList = redisUtil.get(warehouseId +"ckList") == null?new ArrayList<>():(ArrayList)redisUtil.get(warehouseId +"ckList");   //出库
            returnMap.put("ckData",ckList);
//        }
        return returnMap;

    }



    @ApiOperation(value = "一体机查询扫描数据")
    @PostMapping("/api_p/getAllData")
    public HashMap<String,Object> getAllData(HttpServletRequest request){
        HashMap<String,Object> returnMap = new HashMap();
        String ip = BaseUtil.getIPAddress(request);
     /*   DeviceConsoleModel model =  deviceConsoleService.getByIp(ip);
        if (null == model){
            return ;
        }*/
        // warehouseId = model.getWarehouseId().toString();
        String warehouseId ="1";
//        DeviceMachineModel macModel = deviceMachineService.getByIp(ip);

        // ReagentStockModel stockModel = reagentStockService.getByEpcCode(epcCode);
        List<ReagentStock> dataList = new ArrayList<>();
        try{
            List<ReagentStock> rkList = (List<ReagentStock>)redisUtil.get(warehouseId +"rkList") ;   //入库
            if(CollectionUtil.isNotEmpty(rkList)){
                dataList.addAll(rkList);
            }


            List<ReagentStock> ghList = (List<ReagentStock>)redisUtil.get(warehouseId +"ghList");   //归还
            if(CollectionUtil.isNotEmpty(ghList)){
                dataList.addAll(ghList);
            }
            List<ReagentStock> ckList = (List<ReagentStock>)redisUtil.get(warehouseId +"ckList");   //出库
            if(CollectionUtil.isNotEmpty(ckList)){
                dataList.addAll(ckList);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        returnMap.put("data",dataList);
        return returnMap;

    }
















/*

    @ApiIgnore(value = "根据epc编码进行入库、出库和归还操作")
    @PostMapping("/business/searchEpcCode")
    public String searchEpcCode(HttpServletRequest request) {
        List<ReagentEpcVo> epcCodeList = (List<ReagentEpcVo>) redisUtil.get("epcCodeList");//
        List<ReagentEpcVo> ghEcList = (List<ReagentEpcVo>) redisUtil.get("ghList");//入库
        List<ReagentEpcVo> ckEcList = (List<ReagentEpcVo>) redisUtil.get("ckList");//出库
        List<SysLoginModel>  userList = (List<SysLoginModel>)redisUtil.get("userList");
        String showFlag = "0";
        String guide = "0";
        boolean rk = false;
        boolean cg = false;
        if(null != userList && userList.size() > 0){
            for(SysLoginModel model:userList){
                SysLoginModel u = sysLoginService.getById(model.getId());
                if(0==u.getIsWm()){
                    cg = true;
                }else if(1==u.getIsWm()){
                    rk = true;
                }else if(2==u.getIsWm()){
                    cg = true; rk = true;
                }
                if(3 == u.getIsWm()){
                    guide = "1";
                    cg = true; rk = true;
                }
            }
            if(cg && rk){
                showFlag= "2";
            }
            if(!cg && rk){
                showFlag= "1";
            }
            if(cg && !rk){
                showFlag= "0";
            }
        }
        showFlag= "2";
        JSONObject json = new JSONObject();
        json.put("epcCodeList", epcCodeList==null?new ArrayList<ReagentEpcVo>():epcCodeList);
        json.put("ckList", ckEcList==null?new ArrayList<ReagentEpcVo>():ckEcList);
        json.put("ghList", ghEcList==null?new ArrayList<ReagentEpcVo>():ghEcList);

        json.put("totalNum", null == epcCodeList ?"0":epcCodeList.size());// 入库列表总数量
        json.put("showFlag",showFlag);
        json.put("guide",guide);
        return json.toJSONString();
    }
*/





    @ApiImplicitParams({
            @ApiImplicitParam(name="epcCode",value="手机号",required=true),
            @ApiImplicitParam(name="addType",value="添加类型 1出库,2入库",required=true)
    })
    @ApiIgnore(value = "系统后台增加出入库试剂信息")
    @PostMapping("/business/addReaInfo")
    public String addReaInfo(String epcCode,Integer addType) {
        String returnMsg = "";
        try {
            ReagentStock reagentEpc = reagentStockService.getByEpcCode(epcCode);
            String state = reagentStockService.getStateByEpcCode(epcCode);
            List<SysLoginModel>  userMapList = (List<SysLoginModel>)redisUtil.get("userList");

            SysLoginModel sysLoginModel = userMapList.get(0);
            if(reagentEpc != null){
                ReagentEpcVo reagentEpcVo = new ReagentEpcVo();
                reagentEpcVo.setIsDanger(1);//设置是否危险药品
                reagentEpcVo.setEpcCode(epcCode);
                reagentEpcVo.setCName(reagentEpc.getCName());
                reagentEpcVo.setNum(1);
                reagentEpcVo.setIfOut("1");//默认零取

                reagentEpcVo.setRealName(sysLoginModel.getRealName());

                if(1 == addType && state.equals("1")){
                    List<ReagentEpcVo> ckList = (List<ReagentEpcVo>) redisUtil.get("ckList") == null?new ArrayList<>():(List<ReagentEpcVo>) redisUtil.get("ckList");
                    if (ckList != null && ckList.size() > 0) {
                        boolean addFlag = true;
                        for (int i = 0; i < ckList.size(); i++) {
                            if (ckList.get(i).getEpcCode().equals(epcCode)) {
                                addFlag = false;
                            }
                        }
                        if(addFlag){
                            reagentEpcVo.setNum(ckList.size() + 1 );
                            ckList.add(reagentEpcVo);
                            redisUtil.set("ckList", ckList);
                        }
                    }else{
                        ckList.add(reagentEpcVo);
                        redisUtil.set("ckList", ckList);
                    }
                }else if(2 == addType && state.equals("2")){
                    List<ReagentEpcVo> ghList = (List<ReagentEpcVo>) redisUtil.get("ghList")== null?new ArrayList<>():(List<ReagentEpcVo>) redisUtil.get("ghList");;
                    if (ghList != null && ghList.size() > 0) {
                        boolean addFlag = true;
                        for (int i = 0; i < ghList.size(); i++) {
                            if (ghList.get(i).getEpcCode().equals(epcCode)) {
                                addFlag = false;
                            }
                        }
                        if(addFlag){
                            reagentEpcVo.setNum(ghList.size() + 1 );
                            ghList.add(reagentEpcVo);
                            redisUtil.set("ckList", ghList);
                        }
                        redisUtil.set("ghList", ghList);// 把试剂信息重新放进redis中
                    }else{
                        ghList.add(reagentEpcVo);
                        redisUtil.set("ghList", ghList);
                    }
                }else {
                    returnMsg = "试剂状态与出入库功能不符！";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnMsg;
    }

}
